import { _decorator, Component, Node, Collider2D, Contact2DType, IPhysics2DContact } from 'cc';
import { GameTags } from '../constants/GameConstants';
import { Player } from '../entity/Player';
import { EventManager } from '../core/EventManager';

const { ccclass, property } = _decorator;

@ccclass('CollisionSystem')
export class CollisionSystem extends Component {
    @property(Collider2D)
    private collider: Collider2D | null = null;

    private player: Player | null = null;

    start() {
        if (!this.collider) {
            this.collider = this.getComponent(Collider2D);
        }
        this.player = this.getComponent(Player);

        // 注册碰撞回调
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            this.collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
        }
    }

    private onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 检查碰撞对象的标签
        switch (otherCollider.tag) {
            case GameTags.FOOD:
                this.handleFoodCollision(otherCollider.node);
                break;
            case GameTags.ENEMY:
                this.handleEnemyCollision(otherCollider.node);
                break;
        }
    }

    private onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 处理结束碰撞的逻辑
    }

    private handleFoodCollision(foodNode: Node) {
        if (!this.player) return;

        // 获取食物的营养值
        const foodValue = 10; // 这里可以从食物组件中获取具体的值
        
        // 增加进化点数
        this.player.gainEvolutionPoints(foodValue);

        // 销毁食物
        foodNode.destroy();
    }

    private handleEnemyCollision(enemyNode: Node) {
        if (!this.player) return;

        // 根据双方等级和属性判断胜负
        const enemyLevel = 1; // 这里应该从敌人组件中获取
        if (this.player.level >= enemyLevel) {
            // 玩家胜利，获得进化点数
            this.player.gainEvolutionPoints(enemyLevel * 20);
            enemyNode.destroy();
        } else {
            // 玩家失败
            this.player.takeDamage(100);
        }
    }

    onDestroy() {
        if (this.collider) {
            this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            this.collider.off(Contact2DType.END_CONTACT, this.onEndContact, this);
        }
    }
} 